<template>
  <div class="page-editor-container">
    <!-- 顶部工具栏 -->
    <div class="editor-header">
      <el-button icon="el-icon-back" size="small" @click="goBack">返回</el-button>

      <span class="page-title">{{ pageData.title || '新建页面' }}</span>
      <div class="header-actions">
        <el-button
          size="small"
          icon="el-icon-magic-stick"
          style="background-color: #1EB7E6; border-color: #1EB7E6; color: white; margin-right: 10px;"
          @click="handleExtractClick"
        >
          AI提取图片信息
        </el-button>
        <AITask
          ref="aiExtractTask"
          task-name="ai_extract_product_from_image"
          task-display-name="AI图片信息提取"
          dialog-title="AI提取产品图片信息"
          :params="extractImageParams"
          :show-icon="false"
          :show-apply-button="true"
          :enable-image-input="true"
          image-input-label="产品信息输入"
          custom-input-hint="直接粘贴产品图片（Ctrl+V），或点击图片图标上传，AI将自动分析并提取产品标题、描述、关键词、卖点等信息。可以配合文字说明产品名称等。"
          user-content-placeholder="粘贴或上传产品图片，也可以输入产品名称等文字描述..."
          dialog-width="60%"
          style="display: none;"
          @apply="handleExtractApply"
        />
        <CatalogProductImageBatch
          button-text="根据目录册批量生成"
          button-size="small"
          button-icon="el-icon-s-grid"
          style="margin-right: 10px;"
          @apply="handleCatalogBatchApply"
        />
        <el-button type="primary" size="small" :loading="saving" @click="savePage">保存</el-button>
        <el-button
          v-if="pageData.id"
          type="success"
          size="small"
          @click="publishPage"
        >
          发布
        </el-button>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div v-loading="loadingPageData" class="editor-content" element-loading-text="加载页面数据中...">
      <!-- 左侧：页面数据表单 -->
      <div class="left-panel">
        <!-- 创建MD方式：Prompt编辑区域 -->
        <el-card v-if="pageData.deployment_method === 'create_md'" class="prompt-display" shadow="never">
          <el-collapse v-model="activePromptCollapse">
            <el-collapse-item name="prompt">
              <template slot="title">
                <div class="card-header" style="width: 100%; display: flex; justify-content: space-between; align-items: center;">
                  <span style="font-weight: 600;">📝 页面生成Prompt</span>
                  <div @click.stop>
                    <el-button
                      v-if="promptVersions.length > 0"
                      type="text"
                      size="small"
                      icon="el-icon-time"
                      @click="showPromptVersions"
                    >
                      历史版本 ({{ promptVersions.length }})
                    </el-button>
                    <el-button
                      v-if="pageData.page_prompt"
                      type="success"
                      size="small"
                      icon="el-icon-document"
                      @click="handleBuildMD"
                    >
                      构建MD
                    </el-button>
                    <el-button
                      type="text"
                      size="small"
                      icon="el-icon-edit"
                      @click="editPromptDirectly"
                    >
                      直接编辑
                    </el-button>
                  </div>
                </div>
              </template>
              <div v-if="pageData.page_prompt" class="prompt-content">
                {{ pageData.page_prompt }}
              </div>
              <div v-else class="prompt-empty">
                <i class="el-icon-chat-dot-round" />
                <p>尚未生成Prompt，请在右侧与AI对话生成</p>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-card>

        <!-- 页面基本信息 -->
        <el-card class="page-form" shadow="never">
          <div slot="header">
            <span>📄 页面配置</span>
            <el-tag v-if="!isBasicInfoComplete" type="warning" size="mini">请先完成基础信息</el-tag>
          </div>
          <el-form ref="pageForm" :model="pageData" :rules="rules" label-width="100px" size="small">
            <!-- 使用折叠面板组织内容 -->
            <el-collapse v-model="activeCollapse" accordion>
              <!-- 基础信息（默认展开） -->
              <el-collapse-item title="基础信息（必填）" name="basic">
                <template slot="title">
                  <span style="font-weight: 600;">
                    <i class="el-icon-edit" /> 基础信息（必填）
                    <el-tag v-if="!isBasicInfoComplete" type="warning" size="mini" style="margin-left: 10px;">未完成</el-tag>
                    <el-tag v-else type="success" size="mini" style="margin-left: 10px;">已完成</el-tag>
                  </span>
                </template>
                <div class="required-section">
                  <el-form-item label="页面标题" prop="title">
                    <el-input v-model="pageData.title" placeholder="请输入页面标题" @input="handleTitleChange" />
                  </el-form-item>

                  <el-form-item label="URL路径" prop="slug">
                    <el-input
                      v-model="pageData.slug"
                      placeholder="about-us"
                      @input="handleSlugInput"
                      @focus="handleSlugFocus"
                    >
                      <template slot="prepend">
                        <el-button
                          size="mini"
                          icon="el-icon-refresh"
                          title="根据标题重新生成"
                          @click="regenerateSlug"
                        />
                      </template>
                      <template slot="append">.html</template>
                    </el-input>
                    <span class="slug-hint">
                      <i class="el-icon-info" />
                      {{ slugManuallyEdited ? '已手动修改，不再自动生成' : '根据标题自动生成，可手动修改' }}
                    </span>
                  </el-form-item>

                  <el-form-item label="页面类型" prop="page_type">
                    <el-select v-model="pageData.page_type" placeholder="选择页面类型" style="width: 100%">
                      <el-option label="落地页" value="landing" />
                      <el-option label="信息聚合页面（FAQ、解决方案等）" value="info_aggregation" />
                      <el-option label="产品页面" value="product" />
                      <el-option label="产品目录页" value="product_catalog" />
                      <el-option label="目录落地页" value="catalog_landing" />
                      <el-option label="博客文章页面" value="blog_article" />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="内容来源">
                    <el-select v-model="pageData.content_source" placeholder="选择内容来源" style="width: 100%" @change="handleContentSourceChange">
                      <el-option label="手动创建" value="manual" />
                      <el-option label="AI生成" value="ai_generated" />
                      <el-option label="博客文章" value="post" />
                    </el-select>
                    <span class="slug-hint">
                      <i class="el-icon-info" />
                      选择"博客文章"可关联CMS文章自动生成页面
                    </span>
                  </el-form-item>

                  <!-- 博客文章关联 - 仅在content_source为post时显示 -->
                  <el-form-item v-if="pageData.content_source === 'post'" label="关联文章">
                    <el-select
                      v-model="pageData.related_post"
                      filterable
                      remote
                      reserve-keyword
                      placeholder="搜索文章标题"
                      :remote-method="searchPosts"
                      :loading="postLoading"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="post in postList"
                        :key="post.id"
                        :label="post.title"
                        :value="post.id"
                      />
                    </el-select>
                    <span class="slug-hint">
                      <i class="el-icon-info" />
                      选择要关联的博客文章
                    </span>
                  </el-form-item>

                  <el-form-item label="页面语言" prop="language">
                    <el-select v-model="pageData.language" placeholder="选择页面语言" style="width: 100%">
                      <el-option label="英语 (English)" value="en" />
                      <el-option label="中文 (简体)" value="zh-cn" />
                      <el-option label="西班牙语 (Español)" value="es" />
                      <el-option label="法语 (Français)" value="fr" />
                      <el-option label="德语 (Deutsch)" value="de" />
                      <el-option label="日语 (日本語)" value="ja" />
                      <el-option label="韩语 (한국어)" value="ko" />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="页面风格" prop="style">
                    <el-select v-model="pageData.style" placeholder="选择页面风格" style="width: 100%">
                      <el-option label="专业商务" value="professional" />
                      <el-option label="现代简约" value="modern" />
                      <el-option label="友好亲和" value="friendly" />
                      <el-option label="技术性" value="technical" />
                      <el-option label="营销导向" value="marketing" />
                      <el-option label="创意艺术" value="creative" />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="作者风格">
                    <el-select v-model="pageData.writing_style" placeholder="选择文案作者风格（可选）" clearable style="width: 100%">
                      <el-option label="无特殊风格" value="" />
                      <el-option label="史蒂夫·乔布斯 (简洁有力)" value="steve_jobs" />
                      <el-option label="塞斯·高汀 (营销大师)" value="seth_godin" />
                      <el-option label="大卫·奥格威 (广告教父)" value="david_ogilvy" />
                      <el-option label="海明威 (简洁明快)" value="hemingway" />
                      <el-option label="马尔科姆·格拉德威尔 (叙事高手)" value="malcolm_gladwell" />
                      <el-option label="安·汉德利 (内容营销)" value="ann_handley" />
                      <el-option label="尼尔·盖曼 (创意叙事)" value="neil_gaiman" />
                      <el-option label="雷·达里奥 (原则清晰)" value="ray_dalio" />
                    </el-select>
                    <span class="slug-hint">
                      <i class="el-icon-info" />
                      可选：AI生成文案时会模仿所选作者的写作风格
                    </span>
                  </el-form-item>

                  <el-form-item label="业务场景">
                    <el-select v-model="pageData.business_scenario" placeholder="选择业务场景（用于AI分析）" clearable style="width: 100%">
                      <el-option label="B2B 企业服务" value="b2b_service" />
                      <el-option label="B2B 定制方案" value="b2b_custom" />
                      <el-option label="B2B SaaS软件" value="b2b_saas" />
                      <el-option label="B2C 消费品" value="b2c_product" />
                      <el-option label="B2C 电商零售" value="b2c_retail" />
                      <el-option label="通用场景" value="general" />
                    </el-select>
                    <span class="slug-hint">
                      <i class="el-icon-info" />
                      指定业务场景后，AI会针对该场景优化标题、描述和卖点
                    </span>
                  </el-form-item>

                  <el-form-item label="AI提示词">
                    <el-input
                      v-model="pageData.ai_custom_prompt"
                      type="textarea"
                      :rows="3"
                      placeholder="自定义AI分析提示词（可选）&#10;例如：关注企业级客户需求，强调专业性和可定制性"
                    />
                    <span class="slug-hint">
                      <i class="el-icon-info" />
                      自定义提示词会在AI分析图片时使用，帮助AI更准确理解你的需求
                    </span>
                  </el-form-item>

                  <el-form-item label="配色方案">
                    <!-- 网站配色显示 -->
                    <div v-if="websiteData" style="margin-bottom: 10px; padding: 10px; background: #f5f7fa; border-radius: 4px;">
                      <div style="display: flex; align-items: center; gap: 15px; flex-wrap: wrap;">
                        <span style="font-size: 13px; color: #606266;">网站配色：</span>
                        <div style="display: flex; align-items: center; gap: 5px;">
                          <span
                            :style="{
                              display: 'inline-block',
                              width: '24px',
                              height: '24px',
                              borderRadius: '4px',
                              backgroundColor: websiteData.primary_color,
                              border: '1px solid #dcdfe6'
                            }"
                          />
                          <span style="font-size: 12px; color: #909399;">主色 {{ websiteData.primary_color }}</span>
                        </div>
                        <div style="display: flex; align-items: center; gap: 5px;">
                          <span
                            :style="{
                              display: 'inline-block',
                              width: '24px',
                              height: '24px',
                              borderRadius: '4px',
                              backgroundColor: websiteData.secondary_color,
                              border: '1px solid #dcdfe6'
                            }"
                          />
                          <span style="font-size: 12px; color: #909399;">辅助色 {{ websiteData.secondary_color }}</span>
                        </div>
                        <div style="display: flex; align-items: center; gap: 5px;">
                          <span
                            :style="{
                              display: 'inline-block',
                              width: '24px',
                              height: '24px',
                              borderRadius: '4px',
                              backgroundColor: websiteData.accent_color,
                              border: '1px solid #dcdfe6'
                            }"
                          />
                          <span style="font-size: 12px; color: #909399;">强调色 {{ websiteData.accent_color }}</span>
                        </div>
                        <el-checkbox v-model="useWebsiteColors" @change="handleUseWebsiteColors">
                          使用网站配色
                        </el-checkbox>
                      </div>
                    </div>

                    <!-- 页面配色选择器 -->
                    <div style="display: flex; flex-direction: column; gap: 10px;">
                      <!-- 主色 -->
                      <div style="display: flex; align-items: center; gap: 10px;">
                        <span style="width: 60px; font-size: 13px; color: #606266;">主色：</span>
                        <el-color-picker v-model="pageData.primary_color" show-alpha :disabled="useWebsiteColors" />
                        <span style="color: #909399; font-size: 13px;">{{ pageData.primary_color }}</span>
                      </div>
                      <!-- 辅助色 -->
                      <div style="display: flex; align-items: center; gap: 10px;">
                        <span style="width: 60px; font-size: 13px; color: #606266;">辅助色：</span>
                        <el-color-picker v-model="pageData.secondary_color" show-alpha :disabled="useWebsiteColors" />
                        <span style="color: #909399; font-size: 13px;">{{ pageData.secondary_color }}</span>
                      </div>
                      <!-- 强调色 -->
                      <div style="display: flex; align-items: center; gap: 10px;">
                        <span style="width: 60px; font-size: 13px; color: #606266;">强调色：</span>
                        <el-color-picker v-model="pageData.accent_color" show-alpha :disabled="useWebsiteColors" />
                        <span style="color: #909399; font-size: 13px;">{{ pageData.accent_color }}</span>
                      </div>
                      <span v-if="useWebsiteColors" style="font-size: 12px; color: #67C23A;">
                        <i class="el-icon-check" /> 已应用网站配色（主色、辅助色和强调色）
                      </span>
                    </div>
                  </el-form-item>

                  <!-- 保存按钮 -->
                  <el-form-item>
                    <el-button
                      type="primary"
                      icon="el-icon-check"
                      :loading="saving"
                      @click="savePage"
                    >
                      保存基础信息
                    </el-button>
                    <span v-if="lastSaveTime" style="margin-left: 10px; color: #909399; font-size: 12px;">
                      <i class="el-icon-time" /> 上次保存：{{ lastSaveTime }}
                    </span>
                  </el-form-item>
                </div>
              </el-collapse-item>

              <!-- 图片和卖点 -->
              <el-collapse-item name="media">
                <template slot="title">
                  <span style="font-weight: 600;">
                    <i class="el-icon-picture" /> 图片和卖点（可选）
                  </span>
                </template>
                <el-form-item label="主图">
                  <el-input v-model="pageData.product_main_image" placeholder="页面主要展示图片URL">
                    <template slot="prepend">
                      <i class="el-icon-picture" />
                    </template>
                  </el-input>
                  <span class="slug-hint">
                    <i class="el-icon-info" />
                    页面的主要展示图片（产品图、Banner图等），建议尺寸：800x800px或1920x1080px
                  </span>
                </el-form-item>

                <el-form-item label="图册">
                  <el-input
                    v-model="pageData.product_gallery"
                    type="textarea"
                    :rows="3"
                    placeholder="多张展示图片，每行一个URL&#10;https://example.com/image1.jpg&#10;https://example.com/image2.jpg&#10;https://example.com/image3.jpg"
                  />
                  <span class="slug-hint">
                    <i class="el-icon-info" />
                    页面的多角度展示图片（产品图册、案例展示、团队照片等），每行一个URL
                  </span>
                </el-form-item>

                <el-form-item label="核心卖点/亮点">
                  <el-input
                    v-model="pageData.product_highlights"
                    type="textarea"
                    :rows="4"
                    placeholder="请列出页面的核心卖点或亮点，每行一个&#10;例如：&#10;- 高品质材料，耐用持久&#10;- 人体工学设计，舒适体验&#10;- 快速发货，7天无理由退换&#10;- 10年行业经验，值得信赖"
                  />
                  <span class="slug-hint">
                    <i class="el-icon-info" />
                    页面的主要优势和特点（产品卖点、服务优势、品牌特色等），AI会基于这些内容生成页面
                  </span>
                </el-form-item>
              </el-collapse-item>

              <!-- SEO设置 -->
              <el-collapse-item name="seo">
                <template slot="title">
                  <span style="font-weight: 600;">
                    <i class="el-icon-search" /> SEO设置（可选）
                  </span>
                </template>
                <el-form-item label="SEO标题">
                  <el-input v-model="pageData.meta_title" placeholder="留空则使用页面标题" />
                </el-form-item>

                <el-form-item label="SEO描述">
                  <el-input
                    v-model="pageData.meta_description"
                    type="textarea"
                    :rows="2"
                    placeholder="页面简短描述，用于搜索引擎..."
                  />
                </el-form-item>

                <el-form-item label="SEO关键词">
                  <el-input v-model="pageData.meta_keywords" placeholder="关键词1, 关键词2" />
                </el-form-item>
              </el-collapse-item>

              <!-- 其他设置 -->
              <el-collapse-item name="other">
                <template slot="title">
                  <span style="font-weight: 600;">
                    <i class="el-icon-setting" /> 其他设置
                  </span>
                </template>
                <el-form-item label="状态">
                  <el-select v-model="pageData.status" style="width: 100%">
                    <el-option label="草稿" value="draft" />
                    <el-option label="已发布" value="published" />
                    <el-option label="已归档" value="archived" />
                  </el-select>
                </el-form-item>

                <el-form-item label="设为首页">
                  <el-switch v-model="pageData.is_home" />
                </el-form-item>
              </el-collapse-item>
            </el-collapse>
          </el-form>
        </el-card>
      </div>

      <!-- 右侧：AI对话框 -->
      <div class="right-panel">
        <el-card class="ai-chat" shadow="never">
          <div slot="header" class="card-header">
            <span>🤖 AI助手</span>
            <div>
              <el-button
                type="text"
                size="small"
                icon="el-icon-document"
                @click="showPromptSnippets"
              >
                指令片段
              </el-button>
              <el-button
                v-if="conversationHistory.length > 0"
                type="text"
                size="small"
                icon="el-icon-plus"
                @click="saveAsSnippet"
              >
                保存为片段
              </el-button>
              <el-button
                type="text"
                size="small"
                icon="el-icon-refresh"
                @click="resetConversation"
              >
                重新开始
              </el-button>
            </div>
          </div>

          <!-- 对话历史 -->
          <div ref="chatMessages" class="chat-messages">
            <div v-if="conversationHistory.length === 0" class="welcome-message">
              <i class="el-icon-magic-stick" style="font-size: 48px; color: #1EB7E6;" />
              <h3>AI页面Prompt生成助手</h3>
              <p v-if="!isBasicInfoComplete" style="color: #E6A23C;">
                ⚠️ 请先在左侧完成基础信息（语言、风格、主题颜色）
              </p>
              <p v-else>我会通过几个问题帮你生成完整的页面Prompt</p>
              <el-button
                type="primary"
                style="background-color: #1EB7E6; border-color: #1EB7E6;"
                :disabled="!isBasicInfoComplete"
                @click="startConversation"
              >
                开始对话
              </el-button>
            </div>

            <div
              v-for="(msg, index) in conversationHistory"
              :key="index"
              :class="['message', msg.role === 'user' ? 'user-message' : 'ai-message']"
            >
              <div class="message-avatar">
                <i :class="msg.role === 'user' ? 'el-icon-user' : 'el-icon-cpu'" />
              </div>
              <div class="message-content">
                <div class="message-text">{{ msg.content }}</div>
                <div class="message-footer">
                  <span class="message-time">{{ msg.time }}</span>
                  <el-button
                    v-if="msg.role === 'assistant'"
                    type="text"
                    size="mini"
                    icon="el-icon-document-copy"
                    class="copy-button"
                    @click="copyToClipboard(msg.content, index)"
                  >
                    复制
                  </el-button>
                </div>
              </div>
            </div>

            <!-- AI正在输入 -->
            <div v-if="aiTyping" class="message ai-message">
              <div class="message-avatar">
                <i class="el-icon-cpu" />
              </div>
              <div class="message-content">
                <div class="typing-indicator">
                  <span /><span /><span />
                </div>
              </div>
            </div>
          </div>

          <!-- 输入框 -->
          <div class="chat-input">
            <!-- 快捷回复按钮 -->
            <div v-if="conversationHistory.length > 0" class="quick-replies">
              <el-button
                size="mini"
                @click="quickReply('可以')"
              >
                可以
              </el-button>
              <el-button
                size="mini"
                @click="quickReply('以上都是')"
              >
                以上都是
              </el-button>
              <el-button
                size="mini"
                @click="quickReply('还有更多吗？')"
              >
                还有更多吗？
              </el-button>
              <el-button
                size="mini"
                @click="quickReply('没有了')"
              >
                没有了
              </el-button>
              <el-button
                size="mini"
                @click="quickReply('继续')"
              >
                继续
              </el-button>
              <el-button
                size="mini"
                @click="quickReply('请从更垂直关联的方向考虑')"
              >
                请从更垂直关联的方向考虑
              </el-button>
            </div>

            <el-input
              v-model="userInput"
              type="textarea"
              :rows="4"
              placeholder="输入你的回答...&#10;(支持多行输入，点击发送按钮提交)"
              :disabled="aiTyping || conversationHistory.length === 0"
            />
            <div style="margin-top: 10px; display: flex; gap: 10px;">
              <el-button
                type="primary"
                icon="el-icon-s-promotion"
                :loading="aiTyping"
                :disabled="!userInput.trim() || aiTyping || conversationHistory.length === 0"
                style="flex: 1; background-color: #1EB7E6; border-color: #1EB7E6;"
                @click="sendMessage"
              >
                发送
              </el-button>
              <el-button
                type="success"
                icon="el-icon-folder-add"
                :disabled="!userInput.trim()"
                style="width: 140px;"
                @click="quickSaveAsSnippet"
              >
                保存为片段
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 直接编辑Prompt抽屉 -->
    <el-drawer
      title="📝 编辑页面生成Prompt"
      :visible.sync="editPromptDialogVisible"
      direction="rtl"
      size="50%"
      :before-close="handleDrawerClose"
    >
      <div class="drawer-content">
        <el-alert
          title="支持Markdown语法"
          type="info"
          description="您可以使用Markdown语法编辑Prompt，支持标题、列表、加粗、代码块等格式"
          :closable="false"
          show-icon
          style="margin-bottom: 15px;"
        />
        <div v-loading="savingPrompt" element-loading-text="保存中，请稍候...">
          <MarkdownEditor
            :id="'prompt-markdown-editor'"
            v-model="editingPrompt"
            :height="600"
            :disabled="savingPrompt"
            placeholder="输入完整的页面生成Prompt...&#10;&#10;支持Markdown语法：&#10;# 一级标题&#10;## 二级标题&#10;- 列表项&#10;**加粗文本**&#10;`代码`"
          />
        </div>
      </div>
      <div class="drawer-footer">
        <el-button :disabled="savingPrompt" @click="editPromptDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          icon="el-icon-check"
          style="background-color: #1EB7E6; border-color: #1EB7E6;"
          :loading="savingPrompt"
          @click="saveEditedPrompt"
        >
          {{ savingPrompt ? '保存中...' : '保存Prompt' }}
        </el-button>
      </div>
    </el-drawer>

    <!-- 指令片段管理对话框 -->
    <el-dialog
      title="📝 指令片段管理"
      :visible.sync="promptSnippetDialogVisible"
      width="80%"
      top="5vh"
    >
      <div v-loading="loadingSnippets" class="snippet-container">
        <!-- 搜索和筛选 -->
        <div class="snippet-filters" style="margin-bottom: 15px;">
          <el-input
            v-model="snippetSearchKeyword"
            placeholder="搜索片段标题或内容"
            prefix-icon="el-icon-search"
            clearable
            style="width: 300px; margin-right: 10px;"
            @input="searchSnippets"
          />
          <el-button
            type="primary"
            icon="el-icon-plus"
            style="background-color: #1EB7E6; border-color: #1EB7E6;"
            @click="showCreateSnippetDialog"
          >
            新建片段
          </el-button>
        </div>

        <!-- 片段列表 -->
        <div class="snippet-list">
          <el-empty v-if="promptSnippets.length === 0" description="暂无指令片段" />
          <el-card
            v-for="snippet in promptSnippets"
            :key="snippet.id"
            class="snippet-item"
            shadow="hover"
          >
            <div class="snippet-header">
              <h4>{{ snippet.title }}</h4>
              <div class="snippet-actions">
                <el-tag v-if="snippet.category" size="small" type="info">{{ snippet.category }}</el-tag>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-view"
                  @click="viewSnippet(snippet)"
                >
                  查看
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-document-copy"
                  @click="useSnippet(snippet)"
                >
                  使用
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editSnippet(snippet)"
                >
                  编辑
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-delete"
                  style="color: #F56C6C;"
                  @click="deleteSnippet(snippet)"
                >
                  删除
                </el-button>
              </div>
            </div>
            <p class="snippet-preview">{{ snippet.content.substring(0, 100) }}{{ snippet.content.length > 100 ? '...' : '' }}</p>
            <div class="snippet-footer">
              <span><i class="el-icon-time" /> {{ snippet.create_at }}</span>
              <span><i class="el-icon-refresh" /> 使用 {{ snippet.use_count }} 次</span>
            </div>
          </el-card>
        </div>
      </div>

      <div slot="footer">
        <el-button @click="promptSnippetDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 查看指令片段详情对话框 -->
    <el-dialog
      title="指令片段详情"
      :visible.sync="snippetDetailDialogVisible"
      width="60%"
    >
      <div v-if="currentSnippet">
        <h3>{{ currentSnippet.title }}</h3>
        <el-divider />
        <pre style="white-space: pre-wrap; word-wrap: break-word; background: #f5f7fa; padding: 15px; border-radius: 4px;">{{ currentSnippet.content }}</pre>
        <div style="margin-top: 15px;">
          <el-tag v-if="currentSnippet.category" type="info">{{ currentSnippet.category }}</el-tag>
          <span v-if="currentSnippet.tags && currentSnippet.tags.length > 0" style="margin-left: 10px;">
            <el-tag v-for="tag in currentSnippet.tags" :key="tag" size="small" style="margin-right: 5px;">{{ tag }}</el-tag>
          </span>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="snippetDetailDialogVisible = false">关闭</el-button>
        <el-button
          type="primary"
          icon="el-icon-document-copy"
          style="background-color: #1EB7E6; border-color: #1EB7E6;"
          @click="useCurrentSnippet"
        >
          使用此片段
        </el-button>
      </div>
    </el-dialog>

    <!-- 新建/编辑指令片段对话框 -->
    <el-dialog
      :title="snippetFormMode === 'create' ? '新建指令片段' : '编辑指令片段'"
      :visible.sync="snippetFormDialogVisible"
      width="60%"
    >
      <el-form ref="snippetForm" :model="snippetForm" :rules="snippetFormRules" label-width="100px">
        <el-form-item label="片段标题" prop="title">
          <el-input v-model="snippetForm.title" placeholder="请输入片段标题" />
        </el-form-item>
        <el-form-item label="指令内容" prop="content">
          <el-input
            v-model="snippetForm.content"
            type="textarea"
            :rows="10"
            placeholder="请输入指令内容"
          />
        </el-form-item>
        <el-form-item label="分类">
          <el-input v-model="snippetForm.category" placeholder="如:页面生成、内容优化等(可选)" />
        </el-form-item>
        <el-form-item label="标签">
          <el-input v-model="snippetForm.tags" placeholder="多个标签用逗号分隔(可选)" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="snippetFormDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          style="background-color: #1EB7E6; border-color: #1EB7E6;"
          @click="saveSnippet"
        >
          保存
        </el-button>
      </div>
    </el-dialog>

    <!-- Prompt版本历史对话框 -->
    <el-dialog
      title="Prompt历史版本"
      :visible.sync="promptVersionsDialogVisible"
      width="90%"
      top="5vh"
    >
      <!-- 切换视图模式 -->
      <div style="margin-bottom: 15px; display: flex; align-items: center; gap: 15px;">
        <el-radio-group v-model="versionViewMode" size="small">
          <el-radio-button label="timeline">时间线视图</el-radio-button>
          <el-radio-button label="compare">对比视图</el-radio-button>
        </el-radio-group>

        <!-- 对比模式切换（仅在对比视图时显示） -->
        <el-radio-group v-if="versionViewMode === 'compare' && compareVersion" v-model="compareMode" size="small" style="margin-left: auto;">
          <el-radio-button label="side">并排对比</el-radio-button>
          <el-radio-button label="diff">差异高亮</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 时间线视图 -->
      <div v-if="versionViewMode === 'timeline'">
        <el-timeline>
          <el-timeline-item
            v-for="(version, index) in promptVersions"
            :key="version.id"
            :timestamp="version.created_at"
            placement="top"
          >
            <el-card>
              <div slot="header" class="card-header">
                <span>版本 {{ promptVersions.length - index }}</span>
                <div>
                  <el-tag v-if="index === 0" type="success" size="mini">当前版本</el-tag>
                  <el-button
                    v-if="index !== 0"
                    type="text"
                    size="small"
                    icon="el-icon-view"
                    @click="selectVersionForCompare(version)"
                  >
                    与当前对比
                  </el-button>
                  <el-button
                    v-if="index !== 0"
                    type="text"
                    size="small"
                    icon="el-icon-refresh-left"
                    @click="restorePromptVersion(version)"
                  >
                    恢复此版本
                  </el-button>
                </div>
              </div>
              <pre style="white-space: pre-wrap; word-wrap: break-word; max-height: 300px; overflow-y: auto;">{{ version.prompt }}</pre>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>

      <!-- 对比视图 -->
      <div v-else-if="versionViewMode === 'compare'">
        <el-alert
          v-if="!compareVersion"
          title="请选择要对比的版本"
          type="info"
          :closable="false"
          style="margin-bottom: 15px;"
        >
          切换到"时间线视图"，点击历史版本的"与当前对比"按钮
        </el-alert>

        <div v-else>
          <!-- 版本选择器 -->
          <div style="margin-bottom: 15px; display: flex; align-items: center; gap: 15px;">
            <span>对比版本：</span>
            <el-select v-model="selectedCompareVersionId" placeholder="选择历史版本" style="width: 300px;" @change="handleCompareVersionChange">
              <el-option
                v-for="(version, index) in promptVersions.slice(1)"
                :key="version.id"
                :label="`版本 ${promptVersions.length - index - 1} - ${version.created_at}`"
                :value="version.id"
              />
            </el-select>
            <el-button
              size="small"
              icon="el-icon-refresh-left"
              type="primary"
              @click="restorePromptVersion(compareVersion)"
            >
              恢复此版本
            </el-button>
          </div>

          <!-- 并排对比模式 -->
          <div v-if="compareMode === 'side'" style="display: flex; gap: 20px; height: 60vh;">
            <!-- 历史版本（左侧） -->
            <div style="flex: 1; display: flex; flex-direction: column; border: 1px solid #dcdfe6; border-radius: 4px; overflow: hidden;">
              <div style="background: #909399; color: white; padding: 10px; font-weight: 600; display: flex; align-items: center; gap: 8px;">
                <i class="el-icon-time" />
                <span>历史版本 {{ getVersionNumber(compareVersion) }}</span>
                <el-tag size="mini" style="margin-left: auto; background: rgba(255,255,255,0.3); border: none; color: white;">
                  {{ compareVersion && compareVersion.created_at }}
                </el-tag>
              </div>
              <div
                ref="historyScrollContainer"
                style="flex: 1; overflow-y: auto; padding: 15px; background: #fff;"
                @scroll="handleHistoryScroll"
              >
                <pre style="white-space: pre-wrap; word-wrap: break-word; margin: 0; font-family: monospace; line-height: 1.6;">{{ compareVersion && compareVersion.prompt }}</pre>
              </div>
            </div>

            <!-- 当前版本（右侧） -->
            <div style="flex: 1; display: flex; flex-direction: column; border: 1px solid #dcdfe6; border-radius: 4px; overflow: hidden;">
              <div style="background: #67C23A; color: white; padding: 10px; font-weight: 600; display: flex; align-items: center; gap: 8px;">
                <i class="el-icon-check" />
                <span>当前版本</span>
                <el-tag size="mini" style="margin-left: auto; background: rgba(255,255,255,0.3); border: none; color: white;">
                  {{ promptVersions[0] && promptVersions[0].created_at }}
                </el-tag>
              </div>
              <div
                ref="currentScrollContainer"
                style="flex: 1; overflow-y: auto; padding: 15px; background: #f5f7fa;"
                @scroll="handleCurrentScroll"
              >
                <pre style="white-space: pre-wrap; word-wrap: break-word; margin: 0; font-family: monospace; line-height: 1.6;">{{ promptVersions[0] && promptVersions[0].prompt }}</pre>
              </div>
            </div>
          </div>

          <!-- 差异高亮模式 -->
          <div v-else-if="compareMode === 'diff'" style="height: 60vh; border: 1px solid #dcdfe6; border-radius: 4px; overflow: hidden;">
            <code-diff
              :old-string="compareVersion && compareVersion.prompt"
              :new-string="promptVersions[0] && promptVersions[0].prompt"
              :context="10"
              output-format="side-by-side"
            />
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- AI建议对话框（已有Prompt时显示） -->
    <el-dialog
      title="AI建议"
      :visible.sync="aiSuggestionDialogVisible"
      width="60%"
    >
      <el-alert
        title="检测到已有Prompt"
        type="info"
        :closable="false"
        style="margin-bottom: 15px;"
      >
        为保护现有内容，AI仅提供优化建议，请手动复制需要的部分。
      </el-alert>

      <el-card shadow="never" style="background: #f5f7fa; margin-bottom: 15px;">
        <h4>AI建议内容：</h4>
        <pre style="white-space: pre-wrap; word-wrap: break-word;">{{ aiSuggestion }}</pre>
      </el-card>

      <div slot="footer">
        <el-button @click="aiSuggestionDialogVisible = false">关闭</el-button>
        <el-button
          type="primary"
          icon="el-icon-document-copy"
          @click="copyAISuggestion"
        >
          复制建议
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Post, Put, Get, Publish, BuildMD, SavePromptVersion, GetPromptVersions } from '@/api/static_web/page'
import { Get as GetWebsite } from '@/api/static_web/website'
import { getPromptSnippets, createPromptSnippet, updatePromptSnippet, deletePromptSnippet, usePromptSnippet } from '@/api/prompt_snippet'
import AITask from '@/components/AITask/index.vue'
import CatalogProductImageBatch from '@/components/CatalogProductImageBatch/index.vue'
import { CodeDiff } from 'v-code-diff'
import MarkdownEditor from '@/components/MarkdownEditor/index.vue'

export default {
  name: 'PageEditor',
  components: {
    AITask,
    CatalogProductImageBatch,
    MarkdownEditor,
    CodeDiff
  },
  data() {
    return {
      websiteId: null,
      websiteData: null,
      pageId: null,
      hasUnsavedChanges: false, // 是否有未保存的更改
      autoSaveTimer: null, // 自动保存定时器
      loadingPageData: false, // 加载页面数据的loading状态
      savingPrompt: false, // 保存Prompt的loading状态
      saving: false, // 保存页面的loading状态
      lastSaveTime: '', // 上次保存时间
      pageData: {
        id: null,
        website_id: null,
        title: '',
        slug: '',
        page_type: 'landing',
        language: 'en',
        style: 'professional',
        writing_style: '', // 作者风格（可选）
        business_scenario: '', // 业务场景（可选）
        ai_custom_prompt: '', // 自定义AI提示词（可选）
        theme_color: '#1EB7E6',
        // 配色方案
        primary_color: '#1EB7E6',
        secondary_color: '#6c757d',
        accent_color: '#ffc107',
        // 产品信息
        product_main_image: '',
        product_gallery: '',
        product_highlights: '',
        // SEO
        meta_title: '',
        meta_description: '',
        meta_keywords: '',
        page_prompt: '',
        status: 'draft',
        is_home: false,
        // 博客集成
        content_source: 'manual', // 内容来源: manual/ai_generated/post
        related_post: null, // 关联的博客文章ID
        deployment_method: 'create_md', // 部署方式: replace/ai_generate/create_md (默认MD方式)
        template_id: null // 模板ID
      },
      rules: {
        title: [{ required: true, message: '请输入页面标题', trigger: 'blur' }],
        slug: [{ required: true, message: '请输入URL路径', trigger: 'blur' }],
        page_type: [{ required: true, message: '请选择页面类型', trigger: 'change' }],
        language: [{ required: true, message: '请选择页面语言', trigger: 'change' }],
        style: [{ required: true, message: '请选择页面风格', trigger: 'change' }],
        theme_color: [{ required: true, message: '请选择主题颜色', trigger: 'change' }]
      },
      conversationHistory: [],
      userInput: '',
      aiTyping: false,
      editPromptDialogVisible: false,
      editingPrompt: '',
      slugManuallyEdited: false, // 标记slug是否被手动编辑过
      activeCollapse: 'basic', // 默认展开基础信息面板
      activePromptCollapse: ['prompt'], // Prompt折叠面板状态（默认展开）
      useWebsiteColors: false, // 是否使用网站配色
      // 指令片段相关
      promptSnippetDialogVisible: false,
      promptSnippets: [],
      loadingSnippets: false,
      snippetSearchKeyword: '',
      currentSnippet: null,
      snippetDetailDialogVisible: false,
      snippetFormDialogVisible: false,
      snippetFormMode: 'create', // create 或 edit
      snippetForm: {
        id: null,
        title: '',
        content: '',
        category: '',
        tags: ''
      },
      snippetFormRules: {
        title: [{ required: true, message: '请输入片段标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入指令内容', trigger: 'blur' }]
      },
      // Prompt版本控制
      promptVersions: [], // Prompt历史版本
      promptVersionsDialogVisible: false,
      versionViewMode: 'timeline', // 版本视图模式：timeline 或 compare
      compareVersion: null, // 用于对比的历史版本
      selectedCompareVersionId: null, // 选中的对比版本ID
      compareMode: 'side', // 对比模式：side（并排对比）或 diff（差异高亮）
      isSyncingScroll: false, // 是否正在同步滚动（防止循环触发）
      // AI建议
      aiSuggestion: '',
      aiSuggestionDialogVisible: false
    }
  },
  computed: {
    isBasicInfoComplete() {
      return !!(
        this.pageData.title &&
        this.pageData.slug &&
        this.pageData.page_type &&
        this.pageData.language &&
        this.pageData.style &&
        this.pageData.theme_color
      )
    },
    // AI提取图片的参数
    extractImageParams() {
      return {
        image_url: this.pageData.product_main_image || '',
        product_name: this.pageData.title || '',
        business_scenario: this.pageData.business_scenario || '',
        custom_prompt: this.pageData.ai_custom_prompt || ''
      }
    }
  },
  watch: {
    pageData: {
      handler() {
        // 页面数据变化时标记为有未保存的更改
        this.hasUnsavedChanges = true
        // 启动自动保存
        this.scheduleAutoSave()
      },
      deep: true
    },
    conversationHistory: {
      handler() {
        // 对话历史变化时也标记为有未保存的更改
        this.hasUnsavedChanges = true
        this.scheduleAutoSave()
      },
      deep: true
    }
  },
  created() {
    this.websiteId = this.$route.query.website_id
    this.pageId = this.$route.params.id

    if (!this.websiteId) {
      this.$message.error('缺少website_id参数')
      this.$router.back()
      return
    }

    this.pageData.website_id = parseInt(this.websiteId)

    // 加载网站信息
    this.loadWebsiteData()

    // 如果是编辑模式，加载页面数据
    if (this.pageId) {
      this.loadPageData()
    }
  },
  mounted() {
    // 监听浏览器关闭/刷新事件
    window.addEventListener('beforeunload', this.handleBeforeUnload)
  },
  beforeDestroy() {
    // 清理定时器
    if (this.autoSaveTimer) {
      clearTimeout(this.autoSaveTimer)
    }
    // 移除事件监听
    window.removeEventListener('beforeunload', this.handleBeforeUnload)
  },
  beforeRouteLeave(to, from, next) {
    // 路由离开前检查是否有未保存的更改
    if (this.hasUnsavedChanges) {
      this.$confirm('您有未保存的更改，是否保存后再离开？', '提示', {
        confirmButtonText: '保存并离开',
        cancelButtonText: '不保存',
        distinguishCancelAndClose: true,
        type: 'warning'
      }).then(() => {
        // 保存后离开
        this.savePage(true, () => {
          next()
        })
      }).catch((action) => {
        if (action === 'cancel') {
          // 不保存直接离开
          this.hasUnsavedChanges = false
          next()
        } else {
          // 取消离开
          next(false)
        }
      })
    } else {
      next()
    }
  },
  methods: {
    /**
     * 复制内容到剪贴板
     */
    copyToClipboard(content, index) {
      // 使用现代的 Clipboard API
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(content).then(() => {
          this.$message.success('已复制到剪贴板')
        }).catch(err => {
          console.error('复制失败:', err)
          this.fallbackCopyToClipboard(content)
        })
      } else {
        // 降级方案：使用传统方法
        this.fallbackCopyToClipboard(content)
      }
    },

    /**
     * 降级复制方法（兼容旧浏览器）
     */
    fallbackCopyToClipboard(content) {
      const textArea = document.createElement('textarea')
      textArea.value = content
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      try {
        const successful = document.execCommand('copy')
        if (successful) {
          this.$message.success('已复制到剪贴板')
        } else {
          this.$message.error('复制失败，请手动复制')
        }
      } catch (err) {
        console.error('复制失败:', err)
        this.$message.error('复制失败，请手动复制')
      }
      document.body.removeChild(textArea)
    },

    /**
     * 生成URL slug（类似WordPress）
     * 参考：https://github.com/WordPress/WordPress/blob/master/wp-includes/formatting.php#L1941
     */
    generateSlug(title) {
      if (!title) return ''

      let slug = title.toLowerCase()

      // 中文转拼音映射（简化版，实际WordPress使用更复杂的转换）
      const chineseToPinyin = {
        '关于': 'about',
        '联系': 'contact',
        '产品': 'products',
        '服务': 'services',
        '新闻': 'news',
        '博客': 'blog',
        '首页': 'home'
      }

      // 尝试中文关键词映射
      for (const [cn, en] of Object.entries(chineseToPinyin)) {
        if (title.includes(cn)) {
          slug = slug.replace(cn, en)
        }
      }

      // 移除特殊字符，保留字母、数字、空格、连字符
      slug = slug.replace(/[^\w\s-]/g, '')

      // 移除中文字符（如果没有被映射）
      slug = slug.replace(/[\u4e00-\u9fa5]/g, '')

      // 多个空格替换为单个连字符
      slug = slug.replace(/\s+/g, '-')

      // 多个连字符替换为单个连字符
      slug = slug.replace(/-+/g, '-')

      // 移除首尾的连字符
      slug = slug.replace(/^-+|-+$/g, '')

      // 如果生成的slug为空（全是中文），使用时间戳
      if (!slug) {
        slug = 'page-' + Date.now()
      }

      // 限制长度（WordPress默认200字符）
      if (slug.length > 50) {
        slug = slug.substring(0, 50).replace(/-+$/, '')
      }

      return slug
    },

    /**
     * 标题输入时自动生成slug
     */
    handleTitleChange(value) {
      // 只有在新建页面且slug未被手动编辑时才自动生成
      if (!this.pageId && !this.slugManuallyEdited) {
        this.pageData.slug = this.generateSlug(value)
      }
    },

    /**
     * 手动重新生成slug
     */
    regenerateSlug() {
      this.pageData.slug = this.generateSlug(this.pageData.title)
      this.slugManuallyEdited = false // 重置标记，允许继续自动生成
      this.$message.success('已根据标题重新生成URL路径')
    },

    /**
     * slug输入框获得焦点时的处理
     */
    handleSlugFocus() {
      // 当用户点击slug输入框时，标记为即将手动编辑
      // 但暂不设置标记，等待实际输入
    },

    /**
     * slug手动输入时的处理
     */
    handleSlugInput(value) {
      // 用户手动修改了slug，标记为已手动编辑
      if (!this.pageId) {
        this.slugManuallyEdited = true
      }
      // 自动清理slug格式
      this.pageData.slug = this.cleanSlug(value)
    },

    /**
     * 清理slug格式
     */
    cleanSlug(slug) {
      return slug
        .toLowerCase()
        .replace(/[^\w\s-]/g, '')
        .replace(/[\u4e00-\u9fa5]/g, '')
        .replace(/\s+/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-+|-+$/g, '')
    },

    loadWebsiteData() {
      // 获取网站信息，用于设置默认配置
      GetWebsite(this.websiteId).then(response => {
        this.websiteData = response.data

        // 仅在新建页面时，使用网站的配色方案作为默认值并勾选
        if (!this.pageId && this.websiteData.primary_color) {
          this.pageData.primary_color = this.websiteData.primary_color
          this.pageData.secondary_color = this.websiteData.secondary_color || '#6c757d'
          this.pageData.accent_color = this.websiteData.accent_color || '#ffc107'
          this.pageData.theme_color = this.websiteData.primary_color // 向后兼容
          this.useWebsiteColors = true // 默认勾选使用网站配色
        }

        // 使用网站的默认语言
        if (!this.pageId && this.websiteData.default_language) {
          this.pageData.language = this.websiteData.default_language
        }
      }).catch(() => {
        this.$message.warning('获取网站信息失败，将使用默认配置')
      })
    },

    handleUseWebsiteColors(checked) {
      // 当勾选/取消勾选时，应用或恢复颜色
      if (checked && this.websiteData) {
        // 应用网站的配色方案（三个颜色）
        this.pageData.primary_color = this.websiteData.primary_color || '#1EB7E6'
        this.pageData.secondary_color = this.websiteData.secondary_color || '#6c757d'
        this.pageData.accent_color = this.websiteData.accent_color || '#ffc107'
        this.pageData.theme_color = this.websiteData.primary_color || '#1EB7E6' // 向后兼容

        // 强制触发 Vue 响应式更新，确保 AI 对话能获取到最新的颜色值
        this.$forceUpdate()

        this.$message.success('已应用网站配色方案')
      }
    },

    loadPageData() {
      this.loadingPageData = true
      Get(this.pageId).then(response => {
        this.pageData = Object.assign({}, response.data)

        // 🔧 确保 deployment_method 有默认值（因为已移除部署方式选择器，统一使用 create_md）
        if (!this.pageData.deployment_method) {
          this.pageData.deployment_method = 'create_md'
        }

        this.slugManuallyEdited = true // 加载已有页面，标记为已编辑

        // 如果已有prompt，加载到对话历史
        if (this.pageData.page_prompt) {
          this.conversationHistory.push({
            role: 'assistant',
            content: '当前页面已有Prompt。你可以继续对话修改，或点击"重新开始"生成新的Prompt。',
            time: this.getTimeString()
          })
        }
        // 加载版本历史
        this.loadPromptVersions()
      }).catch(() => {
        this.$message.error('加载页面数据失败')
      }).finally(() => {
        this.loadingPageData = false
      })
    },
    startConversation() {
      this.aiTyping = true
      this.callAI('')
    },
    quickReply(text) {
      this.userInput = text
      this.sendMessage()
    },
    sendMessage() {
      if (!this.userInput.trim()) {
        return
      }

      // 添加用户消息
      this.conversationHistory.push({
        role: 'user',
        content: this.userInput,
        time: this.getTimeString()
      })

      const userMessage = this.userInput
      this.userInput = ''
      this.aiTyping = true

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })

      // 调用AI
      this.callAI(userMessage)
    },
    async callAI(userMessage) {
      // 验证基础信息是否完整
      if (!this.isBasicInfoComplete) {
        this.$message.warning('请先完成基础信息（标题、URL、类型、语言、风格、主题颜色）')
        this.aiTyping = false
        return
      }

      try {
        const baseURL = process.env.VUE_APP_BASE_API || ''
        const url = baseURL + '/static_web/api/prompt/generate_interactive/'

        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': this.$store.getters.token,
            'PTOKEN': this.$store.getters.projectId
          },
          body: JSON.stringify({
            website_id: this.websiteId,
            // 页面基础配置
            page_title: this.pageData.title,
            page_slug: this.pageData.slug,
            page_type: this.pageData.page_type,
            language: this.pageData.language,
            style: this.pageData.style,
            writing_style: this.pageData.writing_style,
            business_scenario: this.pageData.business_scenario,
            ai_custom_prompt: this.pageData.ai_custom_prompt,
            // 配色方案
            theme_color: this.pageData.theme_color,
            primary_color: this.pageData.primary_color,
            secondary_color: this.pageData.secondary_color,
            accent_color: this.pageData.accent_color,
            // 产品信息
            product_main_image: this.pageData.product_main_image,
            product_gallery: this.pageData.product_gallery,
            product_highlights: this.pageData.product_highlights,
            // SEO 信息
            meta_title: this.pageData.meta_title,
            meta_description: this.pageData.meta_description,
            meta_keywords: this.pageData.meta_keywords,
            // 其他配置
            status: this.pageData.status,
            is_home: this.pageData.is_home,
            // 对话信息
            user_input: userMessage,
            conversation_history: this.conversationHistory,
            // 现有 Prompt（如果存在）
            existing_prompt: this.pageData.page_prompt || ''
          })
        })

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const reader = response.body.getReader()
        const decoder = new TextDecoder()
        let aiMessage = ''
        let currentMessageIndex = null

        // eslint-disable-next-line no-constant-condition
        while (true) {
          const { done, value } = await reader.read()
          if (done) break

          const chunk = decoder.decode(value)
          const lines = chunk.split('\n')

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.slice(6)
              if (data === '[DONE]') {
                this.aiTyping = false
                break
              }

              try {
                const parsed = JSON.parse(data)
                if (parsed.error) {
                  this.$message.error(parsed.error)
                  this.aiTyping = false
                  break
                }

                if (parsed.content) {
                  aiMessage += parsed.content

                  // 创建或更新AI消息
                  if (currentMessageIndex === null) {
                    this.conversationHistory.push({
                      role: 'assistant',
                      content: aiMessage,
                      time: this.getTimeString()
                    })
                    currentMessageIndex = this.conversationHistory.length - 1
                  } else {
                    this.conversationHistory[currentMessageIndex].content = aiMessage
                  }

                  // 滚动到底部
                  this.$nextTick(() => {
                    this.scrollToBottom()
                  })
                }
              } catch (e) {
                console.error('解析响应失败:', e)
              }
            }
          }
        }

        // 检查是否包含最终Prompt
        if (aiMessage.includes('<start--')) {
          const match = aiMessage.match(/<start--\s*(.*?)\s*--end>/s)
          if (match && match[1]) {
            const newPrompt = match[1].trim()

            // 如果已有Prompt，显示建议而不是直接替换
            if (this.pageData.page_prompt) {
              this.aiSuggestion = newPrompt
              this.aiSuggestionDialogVisible = true
              this.$message.info('AI已生成优化建议，请查看对话框')
            } else {
              // 无Prompt时直接填入
              this.savePromptVersion(newPrompt)
              this.pageData.page_prompt = newPrompt
              this.$message.success('Prompt生成完成！')
            }
          }
        }

        this.aiTyping = false
      } catch (error) {
        console.error('AI调用失败:', error)
        this.$message.error('AI调用失败: ' + error.message)
        this.aiTyping = false
      }
    },
    resetConversation() {
      this.$confirm('确定要重新开始对话吗？当前对话历史将被清空。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.conversationHistory = []
        this.userInput = ''
      })
    },
    // 显示对话历史
    // 显示指令片段列表
    async showPromptSnippets() {
      this.promptSnippetDialogVisible = true
      this.loadingSnippets = true
      try {
        const response = await getPromptSnippets({ pagesize: 100 })
        if (response.success) {
          this.promptSnippets = response.data
        }
      } catch (error) {
        this.$message.error('加载指令片段失败：' + (error.msg || error.message))
      } finally {
        this.loadingSnippets = false
      }
    },
    // 搜索指令片段
    async searchSnippets() {
      this.loadingSnippets = true
      try {
        const params = {
          pagesize: 100
        }
        if (this.snippetSearchKeyword) {
          params.kw = this.snippetSearchKeyword
        }
        const response = await getPromptSnippets(params)
        if (response.success) {
          this.promptSnippets = response.data
        }
      } catch (error) {
        this.$message.error('搜索指令片段失败：' + (error.msg || error.message))
      } finally {
        this.loadingSnippets = false
      }
    },
    // 查看指令片段
    viewSnippet(snippet) {
      this.currentSnippet = snippet
      this.snippetDetailDialogVisible = true
    },
    // 使用指令片段
    async useSnippet(snippet) {
      this.$confirm('确定要使用此指令片段吗？内容将追加到当前输入框。', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(async() => {
        // 追加到输入框
        if (this.userInput) {
          this.userInput += '\n\n' + snippet.content
        } else {
          this.userInput = snippet.content
        }

        // 记录使用
        try {
          await usePromptSnippet(snippet.id)
        } catch (error) {
          console.log('记录使用次数失败', error)
        }

        this.$message.success('指令片段已添加到输入框')
      }).catch(() => {})
    },
    // 使用当前查看的片段
    async useCurrentSnippet() {
      if (!this.currentSnippet) return

      // 追加到输入框
      if (this.userInput) {
        this.userInput += '\n\n' + this.currentSnippet.content
      } else {
        this.userInput = this.currentSnippet.content
      }

      // 记录使用
      try {
        await usePromptSnippet(this.currentSnippet.id)
      } catch (error) {
        console.log('记录使用次数失败', error)
      }

      this.$message.success('指令片段已添加到输入框')
      this.snippetDetailDialogVisible = false
    },
    // 显示新建片段对话框
    showCreateSnippetDialog() {
      this.snippetFormMode = 'create'
      this.snippetForm = {
        id: null,
        title: '',
        content: '',
        category: '',
        tags: ''
      }
      this.snippetFormDialogVisible = true
    },
    // 编辑指令片段
    editSnippet(snippet) {
      this.snippetFormMode = 'edit'
      this.snippetForm = {
        id: snippet.id,
        title: snippet.title,
        content: snippet.content,
        category: snippet.category || '',
        tags: snippet.tags ? snippet.tags.join(',') : ''
      }
      this.snippetFormDialogVisible = true
    },
    // 保存指令片段
    async saveSnippet() {
      this.$refs.snippetForm.validate(async(valid) => {
        if (!valid) return

        try {
          const data = {
            title: this.snippetForm.title,
            content: this.snippetForm.content,
            category: this.snippetForm.category || '',
            tags: this.snippetForm.tags || ''
          }

          let response
          if (this.snippetFormMode === 'create') {
            response = await createPromptSnippet(data)
          } else {
            response = await updatePromptSnippet(this.snippetForm.id, data)
          }

          if (response.success) {
            this.$message.success(this.snippetFormMode === 'create' ? '创建成功' : '更新成功')
            this.snippetFormDialogVisible = false
            // 刷新列表
            this.searchSnippets()
          }
        } catch (error) {
          this.$message.error('保存失败：' + (error.msg || error.message))
        }
      })
    },
    // 删除指令片段
    async deleteSnippet(snippet) {
      this.$confirm(`确定要删除指令片段"${snippet.title}"吗？`, '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          const response = await deletePromptSnippet(snippet.id)
          if (response.success) {
            this.$message.success('删除成功')
            // 刷新列表
            this.searchSnippets()
          }
        } catch (error) {
          this.$message.error('删除失败：' + (error.msg || error.message))
        }
      }).catch(() => {})
    },
    // 快速保存当前输入为片段
    async quickSaveAsSnippet() {
      if (!this.userInput.trim()) {
        this.$message.warning('输入内容不能为空')
        return
      }

      try {
        // 自动生成标题：取前10个字
        const autoTitle = this.userInput.trim().substring(0, 10) + (this.userInput.trim().length > 10 ? '...' : '')

        const data = {
          title: autoTitle,
          content: this.userInput.trim(),
          category: '页面生成',
          tags: ''
        }

        const response = await createPromptSnippet(data)
        if (response.success) {
          this.$message.success('已保存为指令片段')
        }
      } catch (error) {
        this.$message.error('保存失败：' + (error.msg || error.message))
      }
    },
    // 将当前对话保存为片段
    async saveAsSnippet() {
      if (this.conversationHistory.length === 0) {
        this.$message.warning('当前没有对话记录')
        return
      }

      // 获取最后一条AI回复作为内容
      const lastAiMessage = this.conversationHistory.slice().reverse().find(msg => msg.role === 'assistant')
      if (!lastAiMessage) {
        this.$message.warning('没有找到AI回复内容')
        return
      }

      this.snippetFormMode = 'create'
      this.snippetForm = {
        id: null,
        title: `${this.pageData.title || '未命名'} - AI生成指令`,
        content: lastAiMessage.content,
        category: '页面生成',
        tags: ''
      }
      this.snippetFormDialogVisible = true
    },
    handleBuildMD() {
      if (!this.pageData.page_prompt) {
        this.$message.warning('该页面还没有生成 Prompt，无法构建 MD')
        return
      }

      if (!this.pageData.id) {
        this.$message.warning('请先保存页面后再构建 MD')
        return
      }

      this.$confirm('将为此页面生成 .md 配置文件到静态网站目录', '确认生成', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在生成 .md 文件...',
          spinner: 'el-icon-loading'
        })

        BuildMD(this.pageData.id).then(response => {
          loading.close()
          const data = response.data

          // 更新页面状态
          if (data.status) {
            this.pageData.status = data.status
          }

          const messages = [
            `✅ MD 文件生成成功：${data.md_filename}`,
            `📁 图片目录：${data.image_dir}`,
            `🖼️ 生成了 ${data.image_prompts_count} 个图片 Prompt 文件`,
            `📊 页面状态已更新为：MD已创建`
          ]

          this.$notify({
            title: '构建成功',
            message: messages.join('<br/>'),
            dangerouslyUseHTMLString: true,
            type: 'success',
            duration: 5000
          })
        }).catch(error => {
          loading.close()
          console.error('构建 MD 失败:', error)
          this.$message.error(error.msg || '构建 MD 失败')
        })
      }).catch(() => {
        // 用户取消
      })
    },
    editPromptDirectly() {
      this.editingPrompt = this.pageData.page_prompt
      this.editPromptDialogVisible = true
    },
    saveEditedPrompt() {
      // 保存旧的 Prompt（在修改之前）
      const oldPrompt = this.pageData.page_prompt

      // 如果页面还没保存（没有ID），只更新本地
      if (!this.pageData.id) {
        this.pageData.page_prompt = this.editingPrompt
        this.editPromptDialogVisible = false
        this.$message.success('Prompt已更新（请保存页面以持久化）')
        return
      }

      // 检查是否有变化
      if (this.editingPrompt === oldPrompt) {
        this.editPromptDialogVisible = false
        this.$message.info('Prompt未变化')
        console.log('直接编辑：Prompt 无变化')
        return
      }

      // 先保存版本（使用旧的 Prompt 作为基准）
      // 注意：必须在更新 page_prompt 之前保存版本
      console.log('🔄 直接编辑：准备保存新版本')

      // 显示loading状态
      this.savingPrompt = true

      // 直接保存到后端（Put 会更新数据库中的 page_prompt）
      Put(this.pageData.id, {
        page_prompt: this.editingPrompt
      }).then(response => {
        // 更新本地数据
        this.pageData.page_prompt = this.editingPrompt
        this.editPromptDialogVisible = false
        this.$message.success('Prompt已保存')
        console.log('✅ Prompt保存成功')

        // Put 成功后，保存版本历史
        // 此时数据库中的 page_prompt 已经是新值
        // 我们保存新值作为新版本
        this.savePromptVersion(this.editingPrompt, '直接编辑修改')
      }).catch(error => {
        console.error('❌ Prompt保存失败:', error)
        this.$message.error('Prompt保存失败')
      }).finally(() => {
        this.savingPrompt = false
      })
    },
    handleExtractClick() {
      // 直接打开AITask对话框，不需要预先检查图片
      // 用户可以在对话框中上传图片、粘贴图片或输入图片URL
      this.$refs.aiExtractTask.handleShowDialog()
    },
    handleExtractApply(resultData) {
      // resultData包含AI返回的final_result
      const finalResult = resultData.final_result || resultData.content
      console.log('AI提取结果:', finalResult)

      try {
        // 解析JSON结果
        const data = JSON.parse(finalResult)

        // 填充提取的数据到表单
        if (data.title) {
          this.pageData.title = data.title
          // 标题变化后重新生成slug（如果未手动编辑过）
          if (!this.slugManuallyEdited) {
            this.pageData.slug = this.generateSlug(data.title)
          }
        }
        if (data.meta_description) {
          this.pageData.meta_description = data.meta_description
        }
        if (data.keywords && Array.isArray(data.keywords)) {
          this.pageData.meta_keywords = data.keywords.join(', ')
        }
        if (data.selling_points && Array.isArray(data.selling_points)) {
          this.pageData.product_highlights = data.selling_points.join('\n')
        }
        if (data.description) {
          // 可以选择填充到某个字段，比如meta_description如果为空
          if (!this.pageData.meta_description) {
            this.pageData.meta_description = data.description
          }
        }

        this.$message.success('AI提取成功！已自动填充相关信息')
      } catch (error) {
        console.error('解析AI结果失败:', error, '原始数据:', finalResult)
        this.$message.error('解析AI结果失败，请查看控制台')
      }
    },
    handleCatalogBatchApply(data) {
      // data包含批量渲染完成后的结果
      // { main_image, gallery_images, gallery_text }
      console.log('批量生成图片结果:', data)

      try {
        // 应用主图
        if (data.main_image) {
          this.pageData.feature_image = data.main_image
        }

        // 应用图册（每行一个URL）
        if (data.gallery_text) {
          this.pageData.product_gallery = data.gallery_text
        }

        this.$message.success(`已应用批量生成的图片！主图和图册已更新`)
      } catch (error) {
        console.error('应用批量生成结果失败:', error)
        this.$message.error('应用失败，请查看控制台')
      }
    },
    // 处理浏览器关闭/刷新事件
    handleBeforeUnload(e) {
      if (this.hasUnsavedChanges) {
        e.preventDefault()
        e.returnValue = '您有未保存的更改，确定要离开吗？'
        return e.returnValue
      }
    },
    // 自动保存调度
    scheduleAutoSave() {
      // 清除之前的定时器
      if (this.autoSaveTimer) {
        clearTimeout(this.autoSaveTimer)
      }
      // 30秒后自动保存
      this.autoSaveTimer = setTimeout(() => {
        if (this.hasUnsavedChanges && this.pageData.id) {
          this.autoSavePage()
        }
      }, 30000) // 30秒
    },
    // 自动保存
    autoSavePage() {
      if (!this.pageData.id) {
        return // 新页面不自动保存
      }
      console.log('自动保存页面...')
      Put(this.pageData.id, this.pageData).then(() => {
        this.hasUnsavedChanges = false
        this.$message({
          message: '已自动保存',
          type: 'success',
          duration: 1000
        })
      }).catch(() => {
        console.error('自动保存失败')
      })
    },
    savePage(silent = false, callback = null) {
      this.$refs.pageForm.validate((valid) => {
        if (valid) {
          console.log('保存页面数据:', this.pageData)
          console.log('page_prompt内容:', this.pageData.page_prompt)

          this.saving = true // 开始保存

          const saveMethod = this.pageData.id ? Put : Post
          const params = this.pageData.id ? [this.pageData.id, this.pageData] : [this.pageData]

          saveMethod(...params).then(response => {
            // ⚠️ 重要：在 Object.assign 之前保存旧的 Prompt
            const oldPrompt = this.pageData.page_prompt

            // 标记为已保存
            this.hasUnsavedChanges = false
            this.saving = false

            // 更新保存时间
            const now = new Date()
            this.lastSaveTime = now.getFullYear() + '-' +
              String(now.getMonth() + 1).padStart(2, '0') + '-' +
              String(now.getDate()).padStart(2, '0') + ' ' +
              String(now.getHours()).padStart(2, '0') + ':' +
              String(now.getMinutes()).padStart(2, '0') + ':' +
              String(now.getSeconds()).padStart(2, '0')

            if (!silent) {
              this.$message.success('保存成功')
            }
            console.log('保存后完整响应:', response)
            console.log('返回的page_prompt:', response.data?.page_prompt)

            if (!this.pageData.id) {
              // 新建页面，更新ID
              this.pageData.id = response.data.id
              this.pageId = response.data.id
            }
            // 更新本地数据为服务器返回的数据，确保同步
            if (response.data) {
              Object.assign(this.pageData, response.data)
              console.log('更新后的pageData.page_prompt:', this.pageData.page_prompt)
            }

            // 检查 Prompt 是否有变化，如果有则保存版本
            const newPrompt = this.pageData.page_prompt
            console.log('版本检查 - 旧:', oldPrompt ? oldPrompt.substring(0, 50) : 'null')
            console.log('版本检查 - 新:', newPrompt ? newPrompt.substring(0, 50) : 'null')
            console.log('版本检查 - 是否相同:', oldPrompt === newPrompt)

            if (newPrompt && newPrompt !== oldPrompt) {
              // 检查是否已存在相同的版本
              const isDuplicate = this.promptVersions.some(v => v.prompt === newPrompt)
              if (!isDuplicate) {
                console.log('保存新版本到历史')
                this.savePromptVersion(newPrompt)
              } else {
                console.log('版本已存在，跳过保存')
              }
            } else {
              console.log('Prompt 无变化，不保存版本')
            }

            // 执行回调函数（用于路由守卫）
            if (callback) {
              callback()
            }
          }).catch((error) => {
            console.error('保存失败:', error)
            this.saving = false
            this.$message.error('保存失败')
          })
        }
      })
    },
    publishPage() {
      this.$confirm('确定要发布此页面吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        Publish(this.pageData.id).then(() => {
          this.$message.success('发布成功')
          this.pageData.status = 'published'
        })
      })
    },
    goBack() {
      this.$router.push({
        path: '/static_web/pages',
        query: { website_id: this.websiteId }
      })
    },
    /**
     * 部署方式变化处理
     */
    /**
     * 内容来源变化处理
     */
    handleContentSourceChange(value) {
      // 默认使用 create_md 部署方式
      console.log('内容来源切换为:', value)
    },
    /**
     * 根据文章ID获取文章标题
     */
    scrollToBottom() {
      const container = this.$refs.chatMessages
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },
    getTimeString() {
      const now = new Date()
      return `${now.getHours()}:${String(now.getMinutes()).padStart(2, '0')}`
    },
    // ========== Prompt版本控制相关方法 ==========
    savePromptVersion(prompt, notes = '') {
      // 保存Prompt历史版本到后端
      if (!this.pageData.id) {
        console.log('页面未保存，跳过版本保存')
        return
      }

      SavePromptVersion(this.pageData.id, {
        prompt: prompt,
        notes: notes
      }).then(response => {
        if (response.data.saved) {
          console.log('✅ 版本保存成功:', response.msg)
          // 重新加载版本列表
          this.loadPromptVersions()
        } else {
          console.log('ℹ️ 版本未保存:', response.msg)
        }
      }).catch(error => {
        console.error('❌ 保存版本失败:', error)
      })
    },
    loadPromptVersions() {
      // 从后端加载版本历史
      if (!this.pageData.id) {
        return
      }

      GetPromptVersions(this.pageData.id).then(response => {
        this.promptVersions = response.data || []
        console.log(`📚 已加载 ${this.promptVersions.length} 个历史版本`)
      }).catch(error => {
        console.error('❌ 加载版本历史失败:', error)
      })
    },
    showPromptVersions() {
      // 显示Prompt历史版本
      this.versionViewMode = 'timeline' // 默认显示时间线视图
      this.compareVersion = null
      this.selectedCompareVersionId = null
      this.promptVersionsDialogVisible = true
    },
    selectVersionForCompare(version) {
      // 选择版本进行对比
      this.compareVersion = version
      this.selectedCompareVersionId = version.id
      this.versionViewMode = 'compare'
    },
    handleCompareVersionChange(versionId) {
      // 切换对比版本
      this.compareVersion = this.promptVersions.find(v => v.id === versionId)
    },
    getVersionNumber(version) {
      // 获取版本号（后端已经提供了version_number字段）
      if (!version) return ''
      return version.version_number || ''
    },
    restorePromptVersion(version) {
      // 恢复到某个历史版本
      this.$confirm(`确定要恢复到版本 ${version.created_at} 吗？当前版本将被替换。`, '恢复版本', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 保存当前版本到历史
        if (this.pageData.page_prompt) {
          this.savePromptVersion(this.pageData.page_prompt)
        }
        // 恢复选中的版本
        this.pageData.page_prompt = version.prompt
        this.$message.success('版本恢复成功')
      }).catch(() => {
        // 取消操作
      })
    },
    copyAISuggestion() {
      // 复制AI建议内容
      const textarea = document.createElement('textarea')
      textarea.value = this.aiSuggestion
      document.body.appendChild(textarea)
      textarea.select()
      try {
        document.execCommand('copy')
        this.$message.success('已复制到剪贴板')
      } catch (err) {
        this.$message.error('复制失败，请手动复制')
      }
      document.body.removeChild(textarea)
    },
    handleDrawerClose(done) {
      // 关闭抽屉前的确认
      if (this.editingPrompt !== this.pageData.page_prompt) {
        this.$confirm('确定要关闭吗？未保存的更改将丢失。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          done()
        }).catch(() => {
          // 取消关闭
        })
      } else {
        done()
      }
    },
    // ========== 版本对比滚动同步 ==========
    handleHistoryScroll(event) {
      // 历史版本滚动时，同步当前版本的滚动位置
      if (this.isSyncingScroll) return

      this.isSyncingScroll = true
      const historyContainer = event.target
      const currentContainer = this.$refs.currentScrollContainer

      if (currentContainer) {
        // 计算滚动比例
        const scrollPercentage = historyContainer.scrollTop / (historyContainer.scrollHeight - historyContainer.clientHeight)
        // 同步到当前版本容器
        currentContainer.scrollTop = scrollPercentage * (currentContainer.scrollHeight - currentContainer.clientHeight)
      }

      // 使用 requestAnimationFrame 确保滚动完成后再重置标志
      requestAnimationFrame(() => {
        this.isSyncingScroll = false
      })
    },
    handleCurrentScroll(event) {
      // 当前版本滚动时，同步历史版本的滚动位置
      if (this.isSyncingScroll) return

      this.isSyncingScroll = true
      const currentContainer = event.target
      const historyContainer = this.$refs.historyScrollContainer

      if (historyContainer) {
        // 计算滚动比例
        const scrollPercentage = currentContainer.scrollTop / (currentContainer.scrollHeight - currentContainer.clientHeight)
        // 同步到历史版本容器
        historyContainer.scrollTop = scrollPercentage * (historyContainer.scrollHeight - historyContainer.clientHeight)
      }

      // 使用 requestAnimationFrame 确保滚动完成后再重置标志
      requestAnimationFrame(() => {
        this.isSyncingScroll = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page-editor-container {
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.editor-header {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  gap: 15px;

  .page-title {
    font-size: 16px;
    font-weight: 600;
    flex: 1;
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }
}

.editor-content {
  flex: 1;
  display: flex;
  overflow: hidden; /* 防止整体滚动，只允许子元素内部滚动 */
  min-height: 0; /* 确保flex子元素可以正确计算高度 */
}

.left-panel {
  width: 45%;
  padding: 20px;
  padding-bottom: 40px; /* 底部留出更多空间 */
  overflow-y: auto; /* 启用垂直滚动 */
  overflow-x: hidden; /* 隐藏水平滚动 */
  height: 100%; /* 确保占满父容器高度 */

  /* 优化滚动体验 */
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background-color: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #dcdfe6;
    border-radius: 3px;

    &:hover {
      background-color: #c0c4cc;
    }
  }
}

.right-panel {
  width: 55%;
  padding: 20px 20px 20px 0;
  overflow-y: auto; /* 右侧也支持滚动 */
  height: 100%;

  /* 优化滚动体验 */
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background-color: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #dcdfe6;
    border-radius: 3px;

    &:hover {
      background-color: #c0c4cc;
    }
  }
}

.prompt-display {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .prompt-content {
    min-height: 120px;
    max-height: 200px;
    overflow-y: auto;
    padding: 15px;
    background: #f9fafc;
    border-radius: 4px;
    white-space: pre-wrap;
    font-size: 14px;
    line-height: 1.6;
    color: #606266;
  }

  .prompt-empty {
    min-height: 120px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #909399;

    i {
      font-size: 48px;
      margin-bottom: 10px;
      opacity: 0.5;
    }

    p {
      margin: 0;
      font-size: 14px;
    }
  }
}

.ai-chat {
  height: 100%;
  display: flex;
  flex-direction: column;

  ::v-deep .el-card__body {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 0;
    overflow: hidden;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 15px;

    .welcome-message {
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      text-align: center;

      h3 {
        margin: 15px 0 10px;
        color: #303133;
      }

      p {
        color: #909399;
        margin-bottom: 20px;
      }
    }

    .message {
      display: flex;
      gap: 10px;

      &.user-message {
        flex-direction: row-reverse;

        .message-content {
          background: #1EB7E6;
          color: white;
        }

        .message-avatar {
          background: #1EB7E6;
          color: white;
        }
      }

      &.ai-message {
        .message-content {
          background: #f4f4f5;
          color: #303133;
        }

        .message-avatar {
          background: #67c23a;
          color: white;
        }
      }

      .message-avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;

        i {
          font-size: 18px;
        }
      }

      .message-content {
        max-width: 70%;
        padding: 10px 15px;
        border-radius: 8px;

        .message-text {
          white-space: pre-wrap;
          line-height: 1.5;
        }

        .message-footer {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-top: 5px;
          gap: 10px;

          .message-time {
            font-size: 12px;
            opacity: 0.7;
          }

          .copy-button {
            font-size: 12px;
            padding: 0 8px;
            opacity: 0.7;
            transition: opacity 0.2s;

            &:hover {
              opacity: 1;
            }
          }
        }

        // 向后兼容：如果没有 message-footer，直接显示 message-time
        .message-time:not(.message-footer .message-time) {
          font-size: 12px;
          margin-top: 5px;
          opacity: 0.7;
        }
      }
    }

    .typing-indicator {
      display: flex;
      gap: 4px;
      padding: 5px 0;

      span {
        width: 8px;
        height: 8px;
        background: #909399;
        border-radius: 50%;
        animation: typing 1.4s infinite;

        &:nth-child(2) {
          animation-delay: 0.2s;
        }

        &:nth-child(3) {
          animation-delay: 0.4s;
        }
      }
    }
  }

  .chat-input {
    padding: 15px 20px;
    border-top: 1px solid #e4e7ed;

    .quick-replies {
      margin-bottom: 10px;
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .el-button {
        flex-shrink: 0;
        border-radius: 12px;
        background-color: #f5f7fa;
        border-color: #dcdfe6;
        color: #606266;

        &:hover {
          background-color: #1EB7E6;
          border-color: #1EB7E6;
          color: white;
        }
      }
    }
  }
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

.page-form {
  .required-section {
    padding: 15px;
    background: #f9fafc;
    border-radius: 4px;
    margin-bottom: 15px;
    border: 1px dashed #dcdfe6;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .slug-hint {
    font-size: 12px;
    color: #909399;
    margin-left: 5px;

    i {
      margin-right: 3px;
    }
  }
}

// Drawer 样式
.drawer-content {
  padding: 20px;
  height: calc(100% - 80px);
  overflow-y: auto;
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px 20px;
  border-top: 1px solid #e4e7ed;
  background: white;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

// 指令片段样式
.snippet-container {
  min-height: 400px;
  max-height: 70vh;
  overflow-y: auto;
}

.snippet-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 15px;
}

.snippet-item {
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .snippet-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 10px;

    h4 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      flex: 1;
    }

    .snippet-actions {
      display: flex;
      gap: 5px;
      align-items: center;
    }
  }

  .snippet-preview {
    color: #606266;
    font-size: 14px;
    line-height: 1.6;
    margin: 10px 0;
    max-height: 60px;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .snippet-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    color: #909399;
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid #EBEEF5;

    span {
      display: flex;
      align-items: center;
      gap: 5px;
    }
  }
}
</style>
